﻿using DeviceAlarmService.Models;
using DeviceAlarmService.Models.ModbusTcp;
using NModbus;
using System.Net.Sockets;
using DeviceInformation = DeviceAlarmService.Models.ModbusTcp.DeviceInformation;

namespace DeviceAlarmService.DeviceManagement.DeviceConnection.ModbusTcp;

public class ConnectingObjects
{
    IModbusMaster master;

    DeviceInformation device;
    public ConnectingObjects(DeviceInformation deviceInformation)
    {
        this.device = deviceInformation;
    }

    public bool IsConnected
    {
        get
        {
            if (master is null)
            {
                return false;
            }
            return true;

        }
    }
    /// <summary>
    /// 打开连接
    /// </summary>
    /// <param name="device"></param>
    public void Connect()
    {
        try
        {
            if (device.protocol == Protocol.ModbusTcp)
            {
                DeviceAddress deviceAddress = device.deviceAddress;

                TcpClient client = new TcpClient(deviceAddress.ip, deviceAddress.port);

                var factory = new ModbusFactory();

                master = factory.CreateMaster(client);
            }
        }
        catch (Exception ex)
        {
            master = null;
            throw new Exception(ex.Message);
        }
    }

    /// <summary>
    /// 读取Bool
    /// </summary>
    /// <param name="functionCode"></param>
    /// <param name="slaveAddress"></param>
    /// <param name="startAddress"></param>
    /// <param name="numberOfPoints"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public List<bool> ReadBool()
    {
        //获取数据地址
        DataAddress addr = device.dataAddress;

        if (addr.functionCode == FunctionCode.Coils)
        {
            return master.ReadCoils(addr.slaveAddress, addr.startAddress, addr.numberOfPoints).ToList();
        }
        if (addr.functionCode == FunctionCode.Inputs)
        {
            return master.ReadInputs(addr.slaveAddress, addr.startAddress, addr.numberOfPoints).ToList();
        }
        master = null;
        return [false];
    }

    /// <summary>
    /// 关闭连接
    /// </summary>
    public void Close()
    {
        master.Dispose();
    }
}